package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.entity.UserMatch;
import com.yuelao.yuelao_backend.enums.SystemMessageType;
import com.yuelao.yuelao_backend.mapper.UserMatchMapper;
import com.yuelao.yuelao_backend.service.AchievementService;
import com.yuelao.yuelao_backend.service.SystemMessageService;
import com.yuelao.yuelao_backend.service.UserMatchService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.Resource;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户配对Service实现类
 * 重构说明：从UserRelationship拆分出来，专门处理用户配对功能
 */
@Service
public class UserMatchServiceImpl extends ServiceImpl<UserMatchMapper, UserMatch> implements UserMatchService {

    @Resource
    private AchievementService achievementService;
    
    @Resource
    private SystemMessageService systemMessageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createMatch(Long userId1, Long userId2, boolean isSuperMatch) {
        // 检查是否已经配对
        if (isMatched(userId1, userId2)) {
            return true; // 已经配对
        }

        // 创建配对记录（双向）
        UserMatch match1 = new UserMatch();
        match1.setUserId(userId1);
        match1.setMatchedUserId(userId2);
        match1.setIsSuperMatch(isSuperMatch);
        match1.setMatchedAt(LocalDateTime.now());
        match1.setCreatedAt(LocalDateTime.now());
        save(match1);

        UserMatch match2 = new UserMatch();
        match2.setUserId(userId2);
        match2.setMatchedUserId(userId1);
        match2.setIsSuperMatch(isSuperMatch);
        match2.setMatchedAt(LocalDateTime.now());
        match2.setCreatedAt(LocalDateTime.now());
        save(match2);

        // 检查配对相关成就
        achievementService.checkMatchAchievements(userId1, isSuperMatch);
        achievementService.checkMatchAchievements(userId2, isSuperMatch);
        
        // 创建系统消息通知双方配对成功
        java.util.Map<String, Object> extraData1 = new java.util.HashMap<>();
        extraData1.put("matchedUserId", userId2);
        systemMessageService.createMessage(userId1, SystemMessageType.MATCH, "配对成功", "你们互相喜欢，配对成功啦！", extraData1);
        
        java.util.Map<String, Object> extraData2 = new java.util.HashMap<>();
        extraData2.put("matchedUserId", userId1);
        systemMessageService.createMessage(userId2, SystemMessageType.MATCH, "配对成功", "你们互相喜欢，配对成功啦！", extraData2);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeMatch(Long userId1, Long userId2) {
        // 删除双向配对记录
        LambdaQueryWrapper<UserMatch> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(UserMatch::getUserId1, userId1)
                .eq(UserMatch::getUserId2, userId2);
        remove(wrapper1);

        LambdaQueryWrapper<UserMatch> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(UserMatch::getUserId1, userId2)
                .eq(UserMatch::getUserId2, userId1);
        remove(wrapper2);

        return true;
    }

    @Override
    public List<UserMatch> getUserMatches(Long userId) {
        LambdaQueryWrapper<UserMatch> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMatch::getUserId1, userId)
               .orderByDesc(UserMatch::getMatchedAt);
        return list(wrapper);
    }

    @Override
    public boolean isMatched(Long userId1, Long userId2) {
        LambdaQueryWrapper<UserMatch> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMatch::getUserId1, userId1)
               .eq(UserMatch::getUserId2, userId2);
        return count(wrapper) > 0;
    }

    @Override
    public long getTodayNewMatchCount(Long userId) {
        LocalDateTime todayStart = java.time.LocalDate.now().atStartOfDay();
        LambdaQueryWrapper<UserMatch> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMatch::getUserId1, userId)
               .ge(UserMatch::getMatchedAt, todayStart);
        return count(wrapper);
    }

    @Override
    public long countTotalMatches(Long userId) {
        LambdaQueryWrapper<UserMatch> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMatch::getUserId1, userId);
        return count(wrapper);
    }

    @Override
    public long countSuperMatches(Long userId) {
        LambdaQueryWrapper<UserMatch> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMatch::getUserId1, userId)
               .eq(UserMatch::getIsSuperMatch, true);
        return count(wrapper);
    }
}

